﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AsycServer
{
    /// <summary>
    /// 服务端接受数据相关
    /// </summary>
    public partial class AsyUdpServer
    {
        /// <summary>
        /// UDP接收数据的线程执行
        /// </summary>
        void ReceiveThread()
        {
            while (Active)
            {
                try
                {
                    IPEndPoint ip = new IPEndPoint(IPAddress.Any, 0);
                    byte[] data = udpSocket.Receive(ref ip);

                    if (data.Length > 0)
                        ReceiveData(data, ip);
                }
                catch (SocketException e)
                {
                    //CatchException(e);
                    continue;
                }
                catch (Exception e)
                {
                    CatchException(e);
                    continue;
                }
            }
        }

        /// <summary>
        /// 收到数据
        /// </summary>
        /// <param name="data"></param>
        /// <param name="ip"></param>
        void ReceiveData(byte[] data, IPEndPoint ip)
        {
            if (DebugInfo.downData && data.Length > 1)
            {
                string dataString = "";
                foreach (byte b in data) dataString += b + " ";
                Debug("Received " + data.Length + "[" + dataString + "]");
            }

            Client c = GetClient(ip);

            //Pinged
            //数据大小为1字节，并且为255
            if (data.Length == 1 && data[0] == pingByte)
            {
                //判断是否是Ping
                if (c != null && c.Pinging)
                {
                    c.Ping();
                }
                else
                {
                    //不存在角色或者不是Ping，返还数据
                    udpSocket.Send(data, 1, ip);
                }

                return;
            }
            else if (c != null)
            {
                //有对象，把MeesageInfo的数据放入到InMessages中
                inMessages.Add(new MessageInfo(new MessageBuffer(data), ip, this));
            }
            else if (data.Length == 4)
            {
                //没有对象，并且数据长度为4
                int id = BitConverter.ToInt32(data, 0);
                c = GetClient(id);

                if (c != null)
                {
                    if (DebugInfo.acceptData) Debug("Received udp ip for ID " + id);

                    c.udpAdress = ip;
                    //是连接请求
                    connectedList.Add(c);
                }
            }
            else
            {
                inMessagesExternal.Add(new MessageInfo(new MessageBuffer(data), ip, this));
            }

            //累计数据
            downByteBuffer += data.Length;
            downByteTotal += data.Length;
        }
    }
}